package ezonsport.android.ui;

import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

import ezonsport.android.R;
import ezonsport.android.application.EzonSportMobileV2Activity;
import ezonsport.android.common.task.GenericTask;
import ezonsport.android.common.task.TaskAdapter;
import ezonsport.android.common.task.TaskFeedback;
import ezonsport.android.common.task.TaskListener;
import ezonsport.android.common.task.TaskParams;
import ezonsport.android.common.task.TaskResult;
import ezonsport.android.core.stepSystem.SportPlan;
import ezonsport.android.core.stepSystem.StepData;
import ezonsport.android.data.DataHelper;
import ezonsport.android.service.GoalManageService;
import ezonsport.android.service.SportDataService;
import ezonsport.android.service.webservice.HttpException;
import ezonsport.android.ui.userRegister_Login.UserRegisterController;

public class LoginActivity extends OrmLiteBaseActivity<DataHelper> {
	private static final String TAG = "LoginActivity";
	private Button mBtnLogin;
	private Button mBtnRegister;
	private EditText mEditUser;
	private EditText mEditPwd;
	private String mUsername;
	private String mPassword;
	private TextView mProgressText;
	
	private SportDataService service;
	private GoalManageService goalManageService;
	private UserRegisterController mUserController;
	
	// Preferences.
	private SharedPreferences mSharedPre;

	// Tasks.
	private GenericTask mLoginTask;

	//private User user;

	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        mEditUser = (EditText)findViewById(R.id.edit_username);
        mEditPwd = (EditText)findViewById(R.id.edit_password);
        mProgressText = (TextView)findViewById(R.id.login_text_progress);
        mProgressText.setFreezesText(true);
        
        mBtnLogin = (Button)findViewById(R.id.btn_login);
        
     // 初始化数据
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.set(2012, 5, 1);// 开始日期，月份从0开始，即0表示一月份，11表示十二月
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.set(2012, 5, 30);// 结束日期
		service = new SportDataService(getHelper());
		goalManageService = new GoalManageService(getHelper());
		List<StepData> sds = service.getAllStepDatas();
		List<SportPlan> sportPlans = goalManageService.getAllSportPlans();
		// 如果计步数据表中存在数据，则清空，重新添加
		service.deleteAllStepDatas(sds);
		service.addStepData(startCalendar.getTime(), endCalendar.getTime(),
				4000);
		Log.d("Service", "add is successful");

		// 如果运动计划表中存在数据，则清空，重新添加
		goalManageService.deleteAllSportPlans(sportPlans);
		goalManageService.initGoal(2500);
		
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
		    	intent.setClass(LoginActivity.this, EzonSportMobileV2Activity.class);
		    	startActivity(intent);
				//doLogin();			
			}
		});
        mBtnRegister = (Button)findViewById(R.id.btn_register);
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
		    	intent.setClass(LoginActivity.this, RegisterActivity.class);
		    	startActivity(intent);
				
				
			}
		});
        
        mUserController = new UserRegisterController(getHelper()); 
    }
    private void doLogin(){
    	mUsername = mEditUser.getText().toString();
    	mPassword = mEditPwd.getText().toString();
    	
    	if(mLoginTask!=null && mLoginTask.getStatus()==GenericTask.Status.RUNNING)
    		return;
    	else{
    		if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword)) {
				mLoginTask = new LoginTask();
				mLoginTask.setListener(mLoginTaskListener);

				TaskParams params = new TaskParams();
				params.put("username", mUsername);
				params.put("password", mPassword);
				mLoginTask.execute(params);
			} else {
				updateProgress(getString(R.string.login_status_null_username_or_password));
			}
    	}
    		
    }
    
    private void onLoginBegin() {
		disableLogin();
		TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this)
				.start(getString(R.string.login_status_logining_in));
	}
    private void onLoginSuccess(){
    	TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this)
			.success("");
    	updateProgress("");
		mEditUser.setText("");
		mEditPwd.setText("");
		
		Intent intent = new Intent();
    	intent.setClass(LoginActivity.this, EzonSportMobileV2Activity.class);
    	startActivity(intent);
    }
    private void onLoginFailure(String reason) {
		TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this)
				.failed(reason);
		enableLogin();
	}
    private void updateProgress(String progress) {
		mProgressText.setText(progress);
	}
    
    //TaskListener 
    private TaskListener mLoginTaskListener = new TaskAdapter() {

		@Override
		public void onPreExecute(GenericTask task) {
			onLoginBegin();
		}

		@Override
		public void onProgressUpdate(GenericTask task, Object param) {
			updateProgress((String) param);
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			if (result == TaskResult.OK) {
				onLoginSuccess();
			} else {
				onLoginFailure(((LoginTask) task).getMsg());
			}
		}

		@Override
		public String getName() {
			// TODO Auto-generated method stub
			return "Login";
		}
	};
    
    private class LoginTask extends GenericTask {

		private String msg = getString(R.string.login_status_failure);

		public String getMsg() {
			return msg;
		}

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			TaskParams param = params[0];
			//publishProgress(getString(R.string.login_status_logging_in) + "...");

			try {
				String username = param.getString("username");
				String password = param.getString("password");
				//user = EzonSportApplication.mApi.login(username, password);
				
				//EzonSportApplication.getMyselfId(true);
				//EzonSportApplication.getMyselfName(true);
				
				//check the username and pwd
				//未实现WEB同步,预留try...catch
				String msg = mUserController.Login(username, password);
				if(msg == null)
					return TaskResult.OK;
				else
					return TaskResult.FAILED;
					
			} catch (HttpException e) {
				
				return TaskResult.FAILED;
			}

			//SharedPreferences.Editor editor = mPreferences.edit();
			//editor.putString(Preferences.USERNAME_KEY, mUsername);

			// add 存储当前用户的id
			//editor.putString(Preferences.CURRENT_USER_ID, user.getId());
			//editor.commit();

			//return TaskResult.OK;
		}
	}

    private void disableLogin() {
		mEditUser.setEnabled(false);
		mEditPwd.setEnabled(false);
		mBtnLogin.setEnabled(false);
	}
    private void enableLogin() {
		mEditUser.setEnabled(true);
		mEditPwd.setEnabled(true);
		mBtnLogin.setEnabled(true);
	}
    
    public static String encryptPassword(String password) {
		// return Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
		return password;
	}

	public static String decryptPassword(String password) {
		// return new String(Base64.decode(password, Base64.DEFAULT));
		return password;
	}
    
    
 
    
    
}
